﻿
Ext.require(['Ext.data.*', 'Ext.grid.*']);

Ext.define("TaskList", {
    extend: 'Ext.data.Model',
    fields: [{ name: 'Name', type: 'string', convert: seltext }, { name: 'MD5', type: 'string' },
             { name: 'Suffix', type: 'string' }, { name: 'Uploader', type: 'string' },
             { name: 'UploadDate', type: 'string' }, { name: 'ID', type: 'string' }, { name: 'FilePath', type: 'string' }, { name: 'ParentCode', type: 'string' }
        ]
});
var myMask = new Ext.LoadMask('DocumentList', { msg: "加载文档目录,请稍候..." });

Ext.define('State', {
    extend: 'Ext.data.Model',
    fields: [
        { type: 'string', name: 'Name' }
    ]
});

var selModel = Ext.create('Ext.selection.CheckboxModel');

var states = [];  //上传人的数据源
var storeUploader = Ext.create('Ext.data.Store', {
    model: 'State',
    autoLoad: true,
    animate: true,
    data: states
});

var storeTCList = Ext.create('Ext.data.Store', {
    model: "TaskList",
    autoLoad: true,
    animate: true,
    loadMask: false,
    proxy: {
        type: 'ajax',
        actionMethods: { read: 'POST' },
        url: 'Module/DocumentDire.ashx', //数据来源          
        reader: {
            root: 'docArray'
        }
    },
    listeners:
        {
            beforeload: function (store, op, options) {
                var params = {
                    dp: document.getElementById("dirPath").value, //post传参,自定义参数
                    isd: document.getElementById("isDep").value
                };
                Ext.apply(store.proxy.extraParams, params);
                myMask = new Ext.LoadMask('DocumentList', { msg: "加载文档目录,请稍候...", store: storeTCList });
                myMask.show();
            },
            datachanged: function () {
                Ext.getCmp('total').setValue(storeTCList.getCount());
                if (states.length == 0) {
                    storeTCList.each(function (record) {
                        isCon(states, record.get('Uploader'));
                    });
                    storeUploader.loadData(states, false);
                }
            }
        }
});

function isCon(arr, val) {
    var t = 0;
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].Name == val) {
            t++;
            break;
        }
    }
    if (t == 0) {
        arr.push({ Name: val });
    }
}


function SearchDirectory() {
    try {
        var starttime = Ext.getCmp('startTime').getValue() == null ? "" : Ext.getCmp('startTime').getValue().format('yyyy-MM-dd');
        var endtime = Ext.getCmp('endTime').getValue() == null ? "" : Ext.getCmp('endTime').getValue().format('yyyy-MM-dd');
        var ucreate = Ext.getCmp('usercreate').getValue();
        var key = Ext.getCmp('searchTxt').getValue();
        var isd = document.getElementById("isDep").value;
        storeTCList.load({
            params: {
                st: starttime,
                et: endtime,
                u: ucreate,
                k: key,
                isd: isd
            }
        })
    }
    catch (ex) {
        alert("搜索条件的格式出问题");
    }

}
function ResetSearch() {
    Ext.getCmp('startTime').reset();
    Ext.getCmp('endTime').reset();
    Ext.getCmp('usercreate').reset();
    Ext.getCmp('searchTxt').reset();
    //storeTCList.load();
}

var tree;
var grid;
Ext.onReady(function () {
    grid = Ext.create('Ext.grid.Panel', {
        id: "topicCateList",
        height: Ext.getBody().getHeight() - 100,
        renderTo: 'DocumentList',
        rootVisible: false,
        expanded: true,
        dockedItems: [{
            xtype: 'toolbar',
            items: [{
                id: 'refreshBtn',
                text: '刷 新',
                tooltip: '刷 新',
                iconCls: 'arr_refresh',
                handler: function () { storeTCList.load(); }
            }, '-', '上传时间:',
            {
                xtype: 'datefield',
                id: 'startTime',
                width: 100,
                name: 'from_date',
                format: 'Y-m-d',
                value: Ext.Date.add(new Date(), Ext.Date.MONTH, -1),
                maxValue: new Date()  // limited to the current date or prior  
            }, '至',
             {
                 xtype: 'datefield',
                 id: 'endTime',
                 width: 100,
                 name: 'from_date',
                 format: 'Y-m-d',
                 value: Ext.Date.add(new Date(), Ext.Date.DAY, 0),
                 maxValue: new Date()  // limited to the current date or prior  
             },
            '上传人:',
            {
                xtype: "combo",
                name: 'usercreate',
                id: 'usercreate',
                displayField: 'Name',
                valueField: 'Name',
                store: storeUploader,
                triggerAction: 'all',
                queryMode: 'local',
                forceSelection: true, //只允许从下拉列表中进行选择，不能输入文本
                emptyText: '选择上传人',
                blankText: '选择上传人'
            },
            '文档名称:', {
                id: 'searchTxt',
                xtype: 'textfield',
                width: 120,
                emptyText: '输入文档名称',  //为空时的默认显示值
                iconCls: 'moreadd'
            }, '-', {
                id: 'searchBtn',
                text: '搜 索',
                iconCls: 'previewIcon',
                handler: function () { SearchDirectory(); }
            }, {
                id: 'searchEmpty',
                text: '清 空',
                iconCls: 'clear-all',
                handler: function () { ResetSearch(); }
            }
            ]
        }],
        viewConfig: {
            loadMask: false  //设置为false,loading时的Mask自定义       
        },
        store: storeTCList,
        selModel: selModel,
        clicksToEdit: 2,
        columns: [{
            text: '',
            width: 25,
            sortable: true,
            dataIndex: 'Suffix',
            renderer: function (value) {
                return GetFileImage(value);
            }
        }, {
            //            text: '文档名称',
            //            width: '10%',
            //            flex: 2,
            //            sortable: true,
            //            dataIndex: 'Name'

            xtype: 'templatecolumn',
            text: '文档名称',
            flex: 2,
            dataIndex: 'Name',
            sortable: true,
            tpl: new Ext.XTemplate('{Name:this.formatOperate}', {
                formatOperate: function (v) {
                    return v;
                }
            })

        }, {
            text: '所在目录',
            width: 140,
            sortable: true,
            dataIndex: 'FilePath'

        }, {
            text: '上传时间',
            width: 160,
            sortable: true,
            dataIndex: 'UploadDate'
        }, {
            text: '上传人',
            width: 120,
            sortable: true,
            dataIndex: 'Uploader'
        }, {
            xtype: 'templatecolumn',
            text: '操作',
            width: 120,
            dataIndex: 'ID',
            sortable: true,
            tpl: new Ext.XTemplate('{ID:this.formatOperate}', {
                formatOperate: function (v) {
                    return "<a style='text-decoration: underline;color:blue;'" +
                    " onmouseover='this.style.color=\"red\"' onmouseout='this.style.color=\"blue\"'" +
                    " onclick='return DownLoadFileByID(\"" + v + "\")'>浏览 | 下载</a>";
                }
            })
        }],
        bbar: Ext.create('Ext.toolbar.Toolbar', {
            items: [
                '->',
                '文档总数:',
                { xtype: 'textfield', emptyText: '0', id: 'total', readOnly: true },
                { xtype: 'tbspacer', width: 10 }
            ]
        }),
        listeners: {
            itemdblclick: function (view, record, item, index, e, options) {
                var dirPath = document.getElementById("dirPath").value;
                var filePath = dirPath.substr(0, dirPath.lastIndexOf('\\') + 1) + (record.data.ParentCode != "" ? "\\" + record.data.ParentCode + "\\" : "") + record.data.ID + record.data.Suffix;
                var fileName = record.data.Name;
                DownLoadFile(filePath, fileName);
            }
        }
    });

});
function seltext(v, record) {
    return v + record.data.Suffix;
}

//从一个目录转到另一个目录
function GoOtherDirectory(direPath, isdep) {
    document.getElementById("dirPath").value = direPath;
    storeTCList.load({
        params: {
            dp: direPath,
            isd: isdep
        }
    })
}

function DownLoadFile(filePath, fileName) {
    window.location.href = "Module/OpenFile.aspx?fp=" + filePath + "&fn=" + fileName;
    return false;
}

function DownLoadFileByID(fid) {
    var dirPath = document.getElementById("dirPath").value;
    var suffix = ".doc";
    var fileName = "";
    var pcode = "";
    storeTCList.each(function (record) {
        if (record.get('ID') == fid) {
            suffix = record.get('Suffix');
            fileName = record.get('Name')
            pcode = record.get('ParentCode');
        }
    });
    var noRoot = (pcode != "" ? "\\" + pcode + "\\" : "");
    var filePath = dirPath.substr(0, dirPath.lastIndexOf('\\') + 1) + noRoot + fid + suffix;
    DownLoadFile(filePath, fileName);
}


var files = "doc|docx|xls|xlsx|ppt|pptx|pdf|txt|rar|zip|rtf|bmp|gif|jpg";
function GetFileImage(suffix) {
    if (suffix.indexOf('.') == 0) {
        suffix = suffix.substr(1, suffix.length - 1);
    }
    suffix = suffix.toLowerCase();
    if (files.indexOf(suffix) > -1) {
        return "<img src='Style/images/file/" + suffix + ".gif' width='15'/>";
    }
    else {
        return "<img src='Style/images/file/dwg.gif' width='15'/>";
    }
}

Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(), //day
        "h+": this.getHours(), //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format))
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    return format;
}